package cn.itsource.basic.service;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * 只是公共的代码，和spring没有关系
 * @param <T>
 * @param <Q>
 */
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q>{
    /**
     * 注入mapper层
     */
    @Autowired
    private Mapper<T> mapper;

    @Override
    public T findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public PageList<T> findPage(Q q) {
        //1.分页插件
        PageHelper.startPage(q.getCurrentPage(), q.getPageSize());


        //2.查询所有
        List<T> ts = mapper.selectAll();

        if (ts.size() == 0){
            return new PageList<>();
        }

        //3.封装成一个PageInfo对象 插件提供的
        PageInfo<T> pageInfo = new PageInfo<>(ts);

        //4.返回分页结果
        return new PageList<>(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 抽取方法
     *   alt + shift + M
     */
    @Override
    public void saveOrUpdate(T t) {
        //没有id就是新增，有id就是else 修改
        if (t.getId() == null) {
            mapper.insertSelective(t);
        }else {
            mapper.updateByPrimaryKeySelective(t);
        }
    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }



    @Override
    public void batchDelete(Q query) {
        //1.拿到ids
        Long[] ids = query.getIds();

        if (ids == null || ids.length == 0){
            return;
        }

        //2.遍历删除
        for (Long id : ids) {
            mapper.deleteByPrimaryKey(id);
        }

    }



}
